<?php
namespace frontend\controllers;
use common\models\GlobalRegion;
use kartik\datecontrol\DateControl;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frontend\base\BaseFrontController;
use common\models\Board;

/**
 * Site controller
 */
class SiteController extends BaseFrontController
{
	public $enableCsrfValidation = false;
	/**
	 * @inheritdoc
	 */
	public function behaviors()
	{
		return [
				'access' => [
						'class' => AccessControl::className(),
						'only' => [
								'logout',
								'signup'
						],
						'rules' => [
								[
										'actions' => [
												'signup'
										],
										'allow' => true,
										'roles' => [
												'?'
										]
								],
								[
										'actions' => [
												'logout'
										],
										'allow' => true,
										'roles' => [
												'@'
										]
								]
						]
				],
				'verbs' => [
						'class' => VerbFilter::className(),
						'actions' => [
								'logout' => [
										'post'
								]
						]
				]
		];
	}

	/**
	 * @inheritdoc
	 */
	public function actions()
	{
		return [
				'error' => [
						'class' => 'yii\web\ErrorAction'
				],
				'captcha' => [
						'class' => 'yii\captcha\CaptchaAction',
						'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null
				]
		];
	}

	public function actionIndex()
	{
		//$query = (new \yii\db\Query())
    //->from('user')
    // ->where(['email' => 'Smith'])
	//->from('user')
    //->orderBy('id');
    // ->createCommand();
		// foreach ($query->batch() as $users) {
		//     $data[] = $users;
		// }


		// $a = \common\models\User::find()->batch(10);  //每次取 10 条数据
		// var_dump($a);die;
		// $b = \common\models\User::find()->each(10);  //每次取 10 条数据， 迭代查询
		// var_dump($b);die;

// show the SQL statement
// echo $command->sql;
// show the parameters to be bound
// print_r($command->params);
// die;
// returns all rows of the query result
// $rows = $command->queryAll();
// var_dump($data);die;
		$params = [];
		$params['boards'] = $this->buildBoards(0);
//		echo DateControl::widget([
//			'name'=>'kartik-date',
//			'value'=>time(),
//			'type'=>DateControl::FORMAT_TIME,
//			'autoWidget'=>false,
//			'displayFormat' => 'php:D, d-M-Y H:i:s A',
//    'saveFormat' => 'php:U'
//]);die;
		return $this->render('index', $params);
	}

	public function actionTest()
	{
		$model = new SignupForm();
		if ($model->load(Yii::$app->request->post())) {
			if ($user = $model->signup()) {
				if (Yii::$app->getUser()->login($user)) {
					return $this->goHome();
				}
			}
		}

		return $this->render('test', [
			'model' => $model,
		]);
	}


	public function actionLists($id)
	{

		$result = GlobalRegion::find()->where(['parent_id'=>$id])->all();
		$a = '';
		foreach ($result as $data){
			$a .= "<option value='$data->region_id'>$data->region_name</option>";
		}
//		exit($a);
		return Json::encode(['data'=>$a]);

	}

	public function actionTest2()
	{
		$model = new SignupForm();
		if ($model->load(Yii::$app->request->post())) {

		}
		return $this->render('site', [
			'model' => $model,
		]);
	}


	/**
	 * Function output the site that you selected.
	 * @param int $pid
	 * @param int $typeid
	 */
	public function actionSite($pid, $typeid = 0)
	{
		$model = new SignupForm();
//		$model = new Member();
		$model = $model->getCityList($pid);

		if($typeid == 1){$aa="--请选择市--";}else if($typeid == 2){$aa="--请选择区--";}

//		$a = '';

		echo Html::tag('option',$aa, ['value'=>'empty']) ;

		foreach($model as $value=>$name)
		{
			echo Html::tag('option',Html::encode($name),array('value'=>$value));
		}
//		return Json::encode(['data'=>$a]);
	}




	public function actionLogin()
	{
		if (! \Yii::$app->user->isGuest)
		{
			return $this->goHome();
		}

		$model = new LoginForm();
		if ($model->load(Yii::$app->request->post()) && $model->login())
		{
			return $this->goBack();
		}
		else
		{
			return $this->render('login',
					[
							'model' => $model
					]);
		}
	}

	public function actionLogout()
	{
		Yii::$app->user->logout();

		return $this->goHome();
	}

	public function actionContact()
	{
		$model = new ContactForm();
		if ($model->load(Yii::$app->request->post()) && $model->validate())
		{
			if ($model->sendEmail(Yii::$app->params['adminEmail']))
			{
				Yii::$app->session->setFlash('success',
						'Thank you for contacting us. We will respond to you as soon as possible.');
			}
			else
			{
				Yii::$app->session->setFlash('error',
						'There was an error sending email.');
			}

			return $this->refresh();
		}
		else
		{
			return $this->render('contact',
					[
							'model' => $model
					]);
		}
	}

	public function actionAbout()
	{
		return $this->render('about');
	}

	public function actionSignup()
	{
		$model = new SignupForm();
//		var_dump(Yii::$app->request->post());die;
		if ($model->load(Yii::$app->request->post()))
		{
			$user = $model->signup();
			if ($user)
			{
				if (Yii::$app->getUser()->login($user))
				{
					return $this->goHome();
				}
			}
		}

		return $this->render('signup',
				[
						'model' => $model
				]);
	}

	public function actionRequestPasswordReset()
	{
		$model = new PasswordResetRequestForm();
		if ($model->load(Yii::$app->request->post()) && $model->validate())
		{
			if ($model->sendEmail())
			{
				Yii::$app->getSession()->setFlash('success',
						'Check your email for further instructions.');

				return $this->goHome();
			}
			else
			{
				Yii::$app->getSession()->setFlash('error',
						'Sorry, we are unable to reset password for email provided.');
			}
		}

		return $this->render('requestPasswordResetToken',
				[
						'model' => $model
				]);
	}

	public function actionResetPassword($token)
	{
		try
		{
			$model = new ResetPasswordForm($token);
		}
		catch (InvalidParamException $e)
		{
			throw new BadRequestHttpException($e->getMessage());
		}

		if ($model->load(Yii::$app->request->post()) && $model->validate() &&
				 $model->resetPassword())
		{
			Yii::$app->getSession()->setFlash('success',
					'New password was saved.');

			return $this->goHome();
		}

		return $this->render('resetPassword',
				[
						'model' => $model
				]);
	}
}
